package com.healthcarex.hip.saas.message.hl7.v3.util;

import com.healthcarex.hip.saas.message.hl7.v3.namespace.MapNamespaceContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.*;


public class XmlXPathUtil {
    private static final Logger logger = LoggerFactory
            .getLogger(XmlXPathUtil.class);

    /**
     * XML编码
     */
    private String encoding = "utf-8";

    private NamespaceContext defaultNamespaceContext;

    public XmlXPathUtil() {
        defaultNamespaceContext = new MapNamespaceContext();
    }

    public NodeList getListValue(String query, Node xmlDoc,
                                 NamespaceContext nsContext) {
        return (NodeList) evaluate(query, xmlDoc, nsContext,
                XPathConstants.NODESET);
    }

    /**
     * 获取XPath的值
     *
     * @param query
     * @param xmlDoc
     * @param nsContext
     * @return String
     */
    public String getStringValue(String query, Node xmlDoc,
                                 NamespaceContext nsContext) {
        return (String) evaluate(query, xmlDoc, nsContext,
                XPathConstants.STRING);
    }

    public Double getNumberValue(String query, Node xmlDoc,
                                 NamespaceContext nsContext) {
        return (Double) evaluate(query, xmlDoc, nsContext,
                XPathConstants.NUMBER);
    }

    /**
     * 加载XML String资源
     *
     * @param xmlString xml格式的字符串
     * @return Node
     */
    public Document loadXMLResource(String xmlString) {
        if (0xFEFF == xmlString.charAt(0)) {
            xmlString = xmlString.substring(1);
        }
        InputSource source = new InputSource(new BufferedReader(
                new StringReader(xmlString)));
        return this.xmlSourceToDocument(source);
    }

    /**
     * 加载XML byte[]资源
     *
     * @param xmlByte xml文件
     * @return Node
     */
    public Document loadXMLResource(byte xmlByte[]) {
        String xmlString = "";
        try {
            xmlString = new String(xmlByte, encoding);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.toString());
        }
        if (0xFEFF == xmlString.charAt(0)) {
            xmlString = xmlString.substring(1);
        }
        InputSource source = new InputSource(new BufferedReader(
                new StringReader(xmlString)));
        return this.xmlSourceToDocument(source);
    }

    /**
     * 加载XML File资源
     *
     * @param xmlFile xml文件
     * @return Node
     */
    public Document loadXMLResource(File xmlFile) {
        InputSource source = null;
        try {
            source = new InputSource(new FileInputStream(xmlFile));
        } catch (FileNotFoundException e) {
            logger.error(e.toString());
        }
        return this.xmlSourceToDocument(source);
    }

    /**
     * 加载XML InputStream资源
     *
     * @param xmlInputStream xml文件
     * @return Node
     */
    public Document loadXMLResource(InputStream xmlInputStream) {
        InputSource source = new InputSource(xmlInputStream);
        return this.xmlSourceToDocument(source);
    }

    /**
     * 把xml source 转换为Document
     *
     * @param source
     * @return
     */
    private Document xmlSourceToDocument(InputSource source) {
        source.setEncoding(encoding);
        Document document = null;
        try {
            document = loadDocument(source);
        } catch (SAXParseException spe) {
            if (null != spe.getSystemId()) {
                logger.error("xpath解析错误，出错的行数是：" + spe.getLineNumber()
                        + "，uri：" + spe.getSystemId());
                logger.error(spe.getMessage());
            } else {
                logger.error(spe.getMessage());
            }
        } catch (SAXException se) {
            document = null;
            logger.error("解析XML错误，请确保存在格式正确的XML文档。" + se.toString());
        } catch (IOException ioe) {
            document = null;
            logger.error("不能加载文档，文档不可读取。" + ioe.toString());
        }
        return document;
    }

    /**
     * 从InputSource加载document
     *
     * @param source
     * @return Node
     * @throws SAXException
     * @throws IOException
     */
    private Document loadDocument(InputSource source) throws SAXException,
            IOException {
        Document document = null;
        DocumentBuilder parser = null;
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        domFactory.setValidating(false);
        try {
            parser = domFactory.newDocumentBuilder();
        } catch (ParserConfigurationException pce) {
            logger.error(pce.getMessage());
        }
        parser.reset();
        document = parser.parse(source);
        return document;
    }

    /**
     * 设置xml编码
     *
     * @param encoding
     */
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public Node getSingleNodeValue(String query, Node xmlDoc,
                                   NamespaceContext nsContext) {
        return (Node) evaluate(query, xmlDoc, nsContext, XPathConstants.NODE);
    }

    public Object evaluate(String query, Node xmlDoc,
                           NamespaceContext nsContext, QName returnType) {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        if (nsContext == null) {
            nsContext = this.defaultNamespaceContext;
        }
        xpath.setNamespaceContext(nsContext);
        XPathExpression expr;
        try {
            if (StringUtils.isBlank(query)) {
                return null;
            }
            expr = xpath.compile(query);
        } catch (XPathExpressionException xpee) {
            Throwable x = xpee;
            if (null != xpee.getCause()) {
                x = xpee.getCause();
                if ("javax.xml.transform.TransformerException".equals(x.getClass().getName())) {
                    logger.error("xpath:{}", query);
                    logger.error("xpath表达式错误：所有的命名空间需要转换。" + xpee.toString());
                } else {
                    logger.error("xpath表达式错误：可能表达式格式有误。" + xpee.toString());
                }
            }
            return null;
        }
        Object result = null;
        try {
            result = expr.evaluate(xmlDoc, returnType);
            if (result == null) {
//                logger.trace("xpath取值失败：{}", xpath);
            }
        } catch (XPathExpressionException e) {
            logger.error("执行查询语句{}错误。", query);
            logger.error(e.toString());
        }
        return result;
    }
}
